Ext.apply(Ext.form.field.VTypes, {
    account: function(val, field) {
    	var rs  = true;
    	Ext.Ajax.request({
		    url: 'user/userNameIsExistence.do',
		    async: false,
		    params: {
		    	id: field.ownerCt.down('field[name=id]').getValue(),
		    	userName:val
		    },
		    success: function(response){
		        var d = response.responseText;
		        if(d > 0){
		        	rs =  false;
		        }
		    }
		});
    	return rs;
    },
    password: function(val, field){
    	if(val.match('^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$')){
    		return true;
    	}
        return false;
    },
    email:function(val, field){
    	if(val.match('w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*')){
    		return true;
    	}
    	return false;
    },
    emailText:'邮箱地址不合法，请重新输入。',
    accountText: '用户账号已存在。',
    passwordText: '密码应为6-20位的数字加字母组合,。'
});

Ext.define('Module.System.UserManager', {
	extend : 'Ext.panel.Panel',
	alias : 'widget.usermanager',
	layout: 'border',
	border: false,
	initComponent : function() {
		var me = this;
		var enterprise =  Ext.create('Ext.tree.Panel',{
			region: 'west',
			rootVisible: true,
			border: false,
			width: 300,
			region: 'west',
			store: Ext.create('Ext.data.TreeStore', {
//				autoLoad: false,
				fields: ['oname','id','text','name','type','code','addr','icon'],
		        proxy: {
		            type: 'ajax',
		            url: 'enterprise/getEnterprise.do'
		        },
		        root: {
		        	iconCls:'icon-group',
		            id: '0',
		            name: '国网新疆乌鲁木齐供电公司',
		            leaf: false,
		            expanded: true
		        }
		    }),
		    columns: [{
				xtype: 'treecolumn', 
	            sortable: false,
	            flex:1,
	            dataIndex: 'name'
			}],
		    listeners: {
		    	boxready:function(){
		    		enterprise.expandAll();
		    	},
		    	select: function(model,rec){
		    		//usergrid.setTitle(rec.data.text + '---用户列表');
	    			//usergrid.store.proxy.extraParams.eid = rec.data.pid == 0 ? rec.data.id : rec.data.eid;
	    			//usergrid.store.proxy.extraParams.dept = rec.data.id == 0?null:rec.data.id;
	    			var depts = [];
	    			if(rec.childNodes.length > 0){
	    				for ( var i = 0; i < rec.childNodes.length; i++) {
	    					depts[i] = rec.childNodes[i].data.id;
						}
	    			}
	    			
		    		usergrid.store.reload({
	    				params:{
	    					dept:rec.data.id == 0?0:rec.data.id,
	    					depts:depts?depts.join(','):null
	    				}
	    			});
		    	}
		    }
		});
		
		var usergrid = me.usergrid = Ext.create('Ext.grid.Panel',{
			title: '部门用户列表',
			region: 'west',
			width: 600,
			//selModel: Ext.create('Ext.selection.CheckboxModel'),
			region: 'center',
			store: Ext.create('Ext.data.Store', {
				autoLoad: true,
				fields: ['id','account','name','password','ename','enable','createtime','updatetime','updateuser','updateusername',
				         'dept','deptname','counts','phone','email','isconn','locked'],
		        proxy: {
		            type: 'ajax',
		            url: 'user/getUser.do'
		        }
		    }),
			
			tbar: [{
				text: '添加用户',
				iconCls: 'icon-add',
				handler: function(){
					var dept = enterprise.getSelectionModel().getSelection()[0];
					if(dept){
						me.addUser(dept);
					}
					else{
						Ext.Msg.alert('提示', '请选择一个部门！');
					}
				}
			},{
				text: '修改用户',
				iconCls: 'icon-edit',
				handler: function(){
					var dept = enterprise.getSelectionModel().getSelection()[0];
					var recs = usergrid.getSelectionModel().getSelection();
					if(recs.length == 1){
						if(recs[0].raw.id == 0){
							Ext.Msg.alert('提示', '系统默认用户，禁止操作。');
							return;
						}
						me.updateUser(dept,recs[0]);
					}
					else{
						Ext.Msg.alert('提示', '请选择一个用户！');
					}
				}
			},
			{
				text: '用户设置',
				iconCls: 'icon-edit',
				handler: function(){
					var dept = enterprise.getSelectionModel().getSelection()[0];
					var recs = usergrid.getSelectionModel().getSelection();
					if(recs.length == 1){
						if(recs[0].raw.id == 0){
							Ext.Msg.alert('提示', '系统默认用户，禁止操作。');
							return;
						}
						me.setUser(recs);
						Ext.getCmp(me.id+'setWin').setIconCls('icon-edit');
					}
					else{
						Ext.Msg.alert('提示', '请选择一个用户！');
					}
				}
			},
			{
				text: '删除用户',
				iconCls: 'icon-delete',
				handler: function(){
					me.delMenu(usergrid);
				}
			},{
				xtype: 'textfield',
				labelWidth: 48,
				width: 165,
				id:me.id+'inputs',
				fieldLabel: '用户名',
				emptyText: '输入用户名',
				maxLength:16,
				listeners: {
					change: function(f,v){
						usergrid.store.proxy.extraParams.tj = v;
					}
				}
			},{
				iconCls: 'icon-search',
				text: '查询',
				handler: function(){
					usergrid.store.load({params:{
						tj:Ext.getCmp(me.id+'inputs').getValue()
					}});
				}
			}],
		    columns: [{
		    	text: 'ID',
		    	dataIndex: 'id',
		    	width: 80,
		    	hidden: true
		    },{
		    	text: '用户帐户',
		    	dataIndex: 'account',
		    	width:100
		    },{
		    	text: '用户名',
		    	dataIndex: 'name',
		    	width:100
		    },{
		    	text: '部门',
		    	dataIndex: 'deptname',
		    	width:190,
		    	renderer:function(v){
		    		return v == ''?'国网新疆乌鲁木齐供电公司':v;
		    	}
		    },{
		    	text: '连接状态',
		    	dataIndex: 'isconn',
		    	width:80,
		    	renderer:function(v){
		    		return v == 0 ?'<font color="red">离线</font>':'<font color="green">在线</font>';
		    	}
		    },{
		    	text: '锁定状态',
		    	dataIndex: 'locked',
		    	width:80,
		    	renderer:function(v){
		    		return v == 0 ?'<font color="red">锁定</font>':'<font color="green">正常</font>';
		    	}
		    },{
		    	text: '用户状态',
		    	dataIndex: 'enable',
		    	width:80,
		    	renderer:function(v){
		    		return v == 0 ?'<font color="red">已删除</font>':'<font color="green">正常</font>';
		    	}
		    },{
		    	text: '手机',
		    	dataIndex: 'phone',
		    	width:100
		    },{
		    	text: '邮箱',
		    	dataIndex: 'email',
		    	width:120
		    },{
		    	text: '登录次数',
		    	dataIndex: 'counts',
		    	width:80
		    }/*,{
		    	text: '是否可用',
		    	dataIndex: 'enable',
		    	width:100,
		    	renderer: function(v){
		    		return v == 1?'可用':'不可用';
		    	}
		    }*/,{
		    	text: '创建时间',
		    	dataIndex: 'createtime',
		    	width:130,
		    	renderer: function(v){
		    		return Ext.Date.format(new Date(v),'Y-m-d h:m:s');
		    	}
		    },{
		    	text: '更新时间',
		    	dataIndex: 'updatetime',
		    	width:130,
		    	renderer: function(v){
		    		return Ext.Date.format(new Date(v),'Y-m-d h:m:s');
		    	}
		    },{
		    	text: '更新用户',
		    	dataIndex: 'updateusername',
		    	width:100
		    }],
		    listeners: {
		    	select: function(model,rec){
		    		
		    	}
		    }
		});
		me.items = [{
			title: '部门列表',
			region: 'west',
			width: 300,
			layout: 'fit',
			items: enterprise,
			padding: '0 2 0 0'
		},usergrid];
		
		
		me.callParent();
	},
	
	setUser:function(recs){
		var me = this;
		Ext.create('Ext.window.Window',{
			width: 350,
			height: 240,
			modal: true,
			layout: 'fit',
			iconCls: "icon-edit",
			id:me.id+'setWin',
			title: '用户设置',
			buttons: [{
				text: '保存',
				handler: function(){
					var formp = this.up('panel').items.items[0];
        	    	var form = formp.form;
        	    	if(form.isValid()){
        	    		form.submit({
            	    	    url: 'user/setUser.do',
            	    	    success: function(form, action) {
            	    	       var rs = Ext.decode(action.response.responseText);
    	       	    	    	if(rs.rst){
    	       	    	    		Ext.Msg.alert('提示', rs.msg);
    	       	    	    		formp.up('window').close();
    	       	    	    		me.items.items[1].store.reload();
    	       	    	    	}
    	       	    	    	else{
    	       	    	    		Ext.Msg.alert('提示', '保存失败！详情：<br>'+rs.msg);
    	       	    	    	}
            	    	    }
            	    	});
        	    	}
        	    	else{
        	    		Ext.Msg.alert('提示', '用户信息不合法,请填写正确的用户信息。');
        	    	}
				}
			},{
				text: '取消',
				handler: function(){
					this.up('window').close();
				}
			}],
			items: me.getSetUserFrom({
				bodyPadding: 20,
				fileUpload: true,
				border: false,
				listeners: {
					afterrender: function(formp){
						var values = recs[0].raw;
						values.logintimestart = Ext.Date.format(new Date(recs[0].raw.logintimestart),'Y-m-d');
						values.logintimeend = Ext.Date.format(new Date(recs[0].raw.logintimeend),'Y-m-d');
						formp.form.setValues(values);
					}
				}
			})
		}).show();
	},
	addUser: function(dept,rec){
		var me = this;
		Ext.create('Ext.window.Window',{
			width: 500,
			height: 308,
			modal: true,
			layout: 'fit',
			iconCls: "icon-add",
			id:me.id+'userWin',
			title: rec ? "修改用户" : '添加用户',
			buttons: [{
				text: '保存',
				handler: function(){
					var formp = this.up('panel').items.items[0];
        	    	var form = formp.form;
        	    	var account = form.findField('account').getValue();
        	    	var password = form.findField('password').getValue();
        	    	var formdata = form.getValues();
        	    	formdata.password = hex_sha1(password);
        	    	if(account == password){
        	    		Ext.Msg.alert('提示', "密码不能和用户账号相同！");
        	    		return;
        	    	}
        	    	if(form.isValid()){
//        	    		formdata.submit({
//            	    	    url: 'user/addUser.do',
//            	    	    params: {},
//            	    	    success: function(form, action) {
//            	    	       var rs = Ext.decode(action.response.responseText);
//    	       	    	    	if(rs.rst){
//    	       	    	    		Ext.Msg.alert('提示', rs.msg);
//    	       	    	    		formp.up('window').close();
//    	       	    	    		me.items.items[1].store.reload();
//    	       	    	    	}
//    	       	    	    	else{
//    	       	    	    		Ext.Msg.alert('提示', '保存失败！详情：<br>'+rs.msg);
//    	       	    	    	}
//            	    	    }
//            	    	});
        	    		Ext.Ajax.request({
						    url: 'user/addUser.do',
						    params:formdata,
						    success: function(response){
						        var rs = Ext.decode(response.responseText);
						        if(rs.rst){
    	       	    	    		Ext.Msg.alert('提示', rs.msg);
    	       	    	    		formp.up('window').close();
    	       	    	    		me.items.items[1].store.reload();
    	       	    	    	}
    	       	    	    	else{
    	       	    	    		Ext.Msg.alert('提示', '保存失败！详情：<br>'+rs.msg);
    	       	    	    	}
						    }
						});
        	    		
        	    	}
        	    	else{
        	    		Ext.Msg.alert('提示', '用户信息不合法,请填写正确的用户信息。');
        	    	}
				}
			},{
				text: '取消',
				handler: function(){
					this.up('window').close();
				}
			}],
			items: me.getForm({
				bodyPadding: 20,
				fileUpload: true,
				border: false,
				listeners: {
					afterrender: function(formp){
						var values = {};
						if(!rec){
							values.dept = dept.data.id;
							values.ename = dept.data.name == ''?'国网新疆乌鲁木齐供电公司':dept.data.name;
						}else{
							values = rec.data;
							values.ename = rec.data.deptname ==''?'国网新疆乌鲁木齐供电公司':rec.data.deptname;
						}
						formp.form.setValues(values);
						
						formp.down('field[name=ename]').el.on('click',function(){
							me.selectDept(rec,function(rec){
//								formp.form.setValues({dept: values.eid,ename: values.ename});
							});
						});
					}
				}
			})
		}).show();
	},
	updateUser:function(dept,rec){
		var me = this;
		Ext.create('Ext.window.Window',{
			width: 500,
			height: 300,
			modal: true,
			layout: 'fit',
			iconCls: "icon-edit",
			id:me.id+'setWin',
			title: '修改用户',
			buttons: [{
				text: '保存',
				handler: function(){
					var formp = this.up('panel').items.items[0];
        	    	var form = formp.form;
        	    	if(form.isValid()){
        	    		form.submit({
            	    	    url: 'user/addUser.do',
            	    	    success: function(form, action) {
            	    	       var rs = Ext.decode(action.response.responseText);
    	       	    	    	if(rs.rst){
    	       	    	    		Ext.Msg.alert('提示', rs.msg);
    	       	    	    		formp.up('window').close();
    	       	    	    		me.items.items[1].store.reload();
    	       	    	    	}
    	       	    	    	else{
    	       	    	    		Ext.Msg.alert('提示', '保存失败！详情：<br>'+rs.msg);
    	       	    	    	}
            	    	    }
            	    	});
        	    	}
        	    	else{
        	    		Ext.Msg.alert('提示', '用户信息不合法,请填写正确的用户信息。');
        	    	}
				}
			},{
				text: '取消',
				handler: function(){
					this.up('window').close();
				}
			}],
			items: me.getUpdateForm({
				bodyPadding: 20,
				fileUpload: true,
				border: false,
				listeners: {
					afterrender: function(formp){
						var values = {};
						if(!rec){
							values.dept = dept.data.id;
							values.ename = dept.data.name == ''?'国网新疆乌鲁木齐供电公司':dept.data.name;
						}else{
							values = rec.data;
							values.ename = rec.data.deptname ==''?'国网新疆乌鲁木齐供电公司':rec.data.deptname;
						}
						formp.form.setValues(values);
						
						formp.down('field[name=ename]').el.on('click',function(){
							me.selectDept(rec,function(rec){
//								formp.form.setValues({dept: values.eid,ename: values.ename});
							});
						});
					}
				}
			})
		}).show();
	},
	delMenu: function(usergrid){
		var me = this;
		var recs = usergrid.getSelectionModel().getSelection();
		if(recs.length > 0){
			if(recs[0].data.id == 0){
				Ext.Msg.alert('提示', '系统默认用户，禁止操作。');
				return ;
			}
			
			Ext.Msg.confirm('提示', '你确定要删除当前用户吗？',function(b){
				if('yes' == b){
					var users = [];
					var username = [];
					var hascurrent = false;
					for ( var i = 0; i < recs.length; i++) {
						users.push(recs[i].data.id);
						username.push(recs[i].data.name);
						if(recs[i].data.account == user.account){
							hascurrent = true;
						}
					}
					/*if(hascurrent){
						Ext.Msg.confirm('提示', '你将删除当前登录的用户,是否继续?',function(b){
							if('yes' == b){
								me.delUser(users,username,true);
							}
						});
					}*/
//					else{
						me.delUser(users,username);
//					}
				}
			});
		}
		else{
			Ext.Msg.alert('提示', '请选择要删除的用户！');
		}
	},
	delUser: function(users,username,hascurrent){
		var me = this;
		Ext.Ajax.request({
		    url: 'user/deleteUser.do',
		    params: {
		        ids: users.join(','),
		        username:username.join(',')
		    },
		    success: function(response){
		    	var rs = Ext.decode(response.responseText);
		    	if(rs.rst){
		    		Ext.Msg.alert('提示', rs.msg);
		    		if(hascurrent){
		    			Ext.Ajax.request({
		    				url: 'user/logout'
		    			});
		    			window.location = basePath+'login.jsp';
		    		}
		    		me.usergrid.store.reload();
		    	}
		    	else{
		    		Ext.Msg.alert('提示', '保存失败！详情：');
		    	}
		    }
		});
	},
	selectDept: function(urec,callback){
		var me = this;
		Ext.create('Ext.window.Window',{
			width: 500,
			height: 410,
			modal: true,
			layout: 'fit',
			title: '选择目录',
			buttons: [{
				text: '确定',
				handler: function(){
					var node = this.up('window').items.items[0].getSelectionModel().getSelection()[0];
					var formp = Ext.getCmp(me.id+'userWin').down('form');
					var deptName = node.data.depth == 0?'国网新疆乌鲁木齐供电公司':node.data.name;
					formp.form.setValues({dept: node.data.id,ename: deptName});
					if(node){
						callback(node);	
						this.up('window').close();
					}
					else{
						Ext.Msg.alert('提示', '请选择部门！');
					}
				}
			},{
				text: '取消',
				handler: function(){
					this.up('window').close();
				}
			}],
			items: Ext.create('Ext.tree.Panel',{
				rootVisible: true,
				border: false,
				store: Ext.create('Ext.data.TreeStore', {
//					fields: ['id','index','leaf','link','pid','text','linktype'],
					fields: ['oname','id','text','name','type','code','addr','icon'],
			        proxy: {
			            type: 'ajax',
			            url: 'enterprise/getEnterprise.do'
			        },
			        root: {
			            id: 0,
			            iconCls: "icon-group",
			            name: '国网新疆乌鲁木齐供电公司',
			            expanded: true
			        }
			    }),
			    columns: [{
					xtype: 'treecolumn', 
		            sortable: false,
		            flex:1,
		            dataIndex: 'name'
				}]
			})
		}).show();
	},
	getForm: function(config){
		var me = this;
		var formp = Ext.apply({
			region: 'center',
			bodyPadding: 10,
			xtype: 'form',
			defaults: {width: 450,xtype: 'fieldset',layout: 'column'},
			items: [{
				title: '基本信息',
				defaults: {columnWidth: 1,allowBlank: false},
				items: [{
					fieldLabel: '用户ID',
					name: 'id',
					xtype: 'hidden',
					allowBlank: true
				},{
					fieldLabel: '用户账号',
					name: 'account',
					xtype: 'textfield',
					minLength:5,
					maxLength:30,
					padding: '0 0 5 0'
				},{
					fieldLabel: '用户密码',
					name: 'password',
					inputType: 'password',
					xtype: 'textfield',
					regex: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/,
					regexText: "密码应为8-20位的数字和字母组合",
					padding: '0 0 5 0'
				},{
					fieldLabel: '用户名称',
					name: 'name',
					xtype: 'textfield',
					padding: '0 0 5 0',
					minLength:2,
					maxLength:16
				},{
					fieldLabel: '手机号码',
					name: 'phone',
					xtype: 'textfield',
					padding: '0 0 5 0',
					regex:/^1[34578]\d{9}$/,
					regexText: "请输入正确的手机号码",
					maxLength:11,
					minLength:11,
					minValue:1
				},{
					fieldLabel: '邮箱地址',
					name: 'email',
					xtype: 'textfield',
					regex: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
					regexText: "请输入正确的邮箱地址",
					//vtype: 'email',
					padding: '0 0 5 0'
				},{
					fieldLabel: '所属企业',
					name: 'eid',
					xtype: 'hidden',
					padding: '0 0 5 0'
				},{
					fieldLabel: '所属部门',
					name: 'ename',
					xtype: 'textfield',
					padding: '0 0 5 0',
					id:'enameId',
					readOnly: true
				},{
					fieldLabel: 'dept',
					name: 'dept',
					xtype: 'hidden',
					allowBlank: true
				},{
					fieldLabel: '序号',
					name: 'index',
					xtype: 'hidden',
					padding: '0 0 5 0'
				}]
			}]
		},config);
		
		return formp;
	},
	getUpdateForm: function(config){
		var me = this;
		var formp = Ext.apply({
			region: 'center',
			bodyPadding: 10,
			xtype: 'form',
			defaults: {width: 450,xtype: 'fieldset',layout: 'column'},
			items: [{
				title: '基本信息',
				defaults: {columnWidth: 1,allowBlank: false},
				items: [{
					fieldLabel: '用户ID',
					name: 'id',
					xtype: 'hidden',
					allowBlank: true
				},{
					fieldLabel: '用户账号',
					name: 'account',
					xtype: 'textfield',
					minLength:5,
					maxLength:30,
					padding: '0 0 5 0'
				},{
					fieldLabel: '用户名称',
					name: 'name',
					xtype: 'textfield',
					padding: '0 0 5 0',
					minLength:2,
					maxLength:16
				},{
					fieldLabel: '手机号码',
					name: 'phone',
					xtype: 'textfield',
					padding: '0 0 5 0',
					regex:/^1[34578]\d{9}$/,
					regexText: "请输入正确的手机号码",
					maxLength:11,
					minLength:11,
					minValue:1
				},{
					fieldLabel: '邮箱地址',
					name: 'email',
					xtype: 'textfield',
					regex: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
					regexText: "请输入正确的邮箱地址",
					//vtype: 'email',
					padding: '0 0 5 0'
				},{
					fieldLabel: '所属企业',
					name: 'eid',
					xtype: 'hidden',
					padding: '0 0 5 0'
				},{
					fieldLabel: '所属部门',
					name: 'ename',
					xtype: 'textfield',
					padding: '0 0 5 0',
					id:'enameId',
					readOnly: true
				},{
					fieldLabel: 'dept',
					name: 'dept',
					xtype: 'hidden',
					allowBlank: true
				},{
					fieldLabel: '序号',
					name: 'index',
					xtype: 'hidden',
					padding: '0 0 5 0'
				}]
			}]
		},config);
		
		return formp;
	},
	getSetUserFrom : function(config){
		var formp = Ext.apply({
			region: 'center',
			bodyPadding: 10,
			xtype: 'form',
			defaults: {width: 350,xtype: 'fieldset',layout: 'column'}, 
			title: '',
			defaults: {columnWidth: 1,allowBlank: false},
			items: [{
						fieldLabel: '用户ID',
						name: 'id',
						xtype: 'hidden',
						allowBlank: true
					},{
						fieldLabel: '用户账号',
						name: 'account',
						xtype: 'hidden',
						allowBlank: true
					},{
						fieldLabel: '用户名',
						name: 'name',
						xtype: 'hidden',
						allowBlank: true
					},new Ext.form.NumberField({  
		                fieldLabel:'密码过期天数', 
		                name: 'passtime',
		                maxValue:90,                       //最大值  
		                maxText:'值太大',  
		                minValue:1,                        //最小值  
		                minText:'值太小'  
		            }),new Ext.form.NumberField({  
		                fieldLabel:'允许密码错次', 
		                name: 'lockcount',
		                maxValue:10,                       //最大值  
		                maxText:'值太大',  
		                minValue:1,                        //最小值  
		                minText:'值太小'  
		            }),{
						fieldLabel: '允许登陆ip',
						name: 'enableip',
						xtype: 'textfield',
						regex: /((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)/,
						regexText: "请输入正确ip地址",
						padding: '0 0 5 0'
					},
					{
						fieldLabel: '访问起始时间',
						name: 'logintimestart',
						xtype: 'datefield',
						format:'Y-m-d',
						padding: '0 0 5 0',
					},
					{
						fieldLabel: '访问结束时间',
						name: 'logintimeend',
						xtype: 'datefield',
						format:'Y-m-d',
						padding: '0 0 5 0',
					},
		    ],  
		},config); 
		return formp;
	}
	
});